package com.bang.study.service.impl;

import com.bang.study.entity.MsgLog;
import com.bang.study.mapper.MsgLogMapper;
import com.bang.study.service.IMsgLogService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 消息投递日志 服务实现类
 * </p>
 *
 * @author bang
 * @since 2020-01-16
 */
@Service
public class MsgLogServiceImpl extends ServiceImpl<MsgLogMapper, MsgLog> implements IMsgLogService {


    @Override
    public void updateStatus(String msgId, Integer status) {
        MsgLog msgLog = new MsgLog();
        msgLog.setMsgId(msgId);
        msgLog.setStatus(status);
        msgLog.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateStatus(msgLog);
    }

    @Override
    public MsgLog selectByMsgId(String msgId) {
        return  this.baseMapper.selectById(msgId);
    }

    @Override
    public List<MsgLog> selectTimeoutMsg() {
        QueryWrapper<MsgLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MsgLog::getStatus, 0).lt(MsgLog::getNextTryTime, LocalDateTime.now());
        return  this.list(queryWrapper);
    }

    @Override
    public void updateTryCount(String msgId, LocalDateTime tryTime) {

        LocalDateTime nextTryTime = tryTime.plusMinutes(1L);

        MsgLog msgLog = new MsgLog();
        msgLog.setMsgId(msgId);
        msgLog.setNextTryTime(nextTryTime);
        this.baseMapper.updateTryCount(msgLog);
    }
}
